<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { jwtDecode } from 'jwt-decode'

interface Disease {
  id: number
  name: string
  direction: number
  category: number
}

interface Article {
  id: number
  name: string
  content: string
  cover: string
  disease: number
  category: number
  direction: number
}

const route = useRoute()
const router = useRouter()
const diseaseId = ref(parseInt(route.params.diseaseId as string))
const disease = ref<Disease | null>(null)
const diseases = ref<Disease[]>([])
const articles = ref<Article[]>([])
const currentPage = ref(1)
const totalPages = ref(1)
const searchQuery = ref('')
const loading = ref(false)
const error = ref('')
const username = ref<string | null>(null)
const avatar = ref<string | null>(null)

const navigationItems = [
  { name: '问医生', link: '/sections' },
  { name: '查疾病', link: '/disease' },
  { name: '查药品', link: '/medicine' },
  { name: '查医院', link: '/hospital' },
  { name: '查检查/手术', link: '/examination' },
  { name: '查疫苗', link: '/vaccine' },
  { name: '急救指南', link: '/emergency' },
  { name: '测一测', link: '/test' },
  { name: '科普视频', link: '/videos' }
]
// 登录
const fetchUserInfo = async () => {
  const token = localStorage.getItem('token');
  if (token) {
    const payload = ref<any>(jwtDecode(token));
    username.value = payload.value.username;
    avatar.value = 'http://127.0.0.1:8000/uploads/' + payload.value.avatar;
    console.log(avatar.value);
  }

}

const logout = () => {
  localStorage.removeItem('token');
  username.value = null;
  avatar.value = null;
};


// Fetch all diseases in the same category
const fetchDiseases = async () => {
  if (!disease.value) return

  try {
    const response = await fetch(`http://127.0.0.1:8000/disease/disease/${disease.value.direction}/${disease.value.category}/`)
    if (!response.ok) {
      throw new Error('Failed to fetch diseases')
    }
    diseases.value = await response.json()
  } catch (err) {
    console.error('Error fetching diseases:', err)
  }
}

// Fetch disease details and related articles
const fetchDiseaseData = async () => {
  loading.value = true
  error.value = ''

  try {
    const diseaseResponse = await fetch(`http://127.0.0.1:8000/disease/disease/0/0/`)
    if (!diseaseResponse.ok) {
      throw new Error('Failed to fetch disease data')
    }
    const allDiseases = await diseaseResponse.json()
    const currentDisease = allDiseases.find((d: Disease) => d.id === diseaseId.value)

    if (!currentDisease) {
      throw new Error('未找到疾病')
    }

    disease.value = currentDisease
    await fetchDiseases()
    await fetchArticles()
  } catch (err) {
    error.value = err instanceof Error ? err.message : '发生错误'
    console.error('获取疾病数据错误:', err)
  } finally {
    loading.value = false
  }
}

const selectDisease = async (selectedDisease: Disease) => {
  router.push(`/disease/${selectedDisease.id}`)
}

const fetchArticles = async () => {
  if (!disease.value) return

  loading.value = true
  error.value = ''

  try {
    const response = await fetch(
      `http://127.0.0.1:8000/disease/message/${disease.value.direction}/${disease.value.category}/${disease.value.id}/?page=${currentPage.value}`
    )
    if (!response.ok) {
      throw new Error('获取文章列表失败')
    }
    const data = await response.json()
    articles.value = data.results
    totalPages.value = Math.ceil(data.count / data.page_size)
  } catch (err) {
    error.value = err instanceof Error ? err.message : '发生错误'
    console.error('获取文章列表失败:', err)
  } finally {
    loading.value = false
  }
}

const changePage = async (page: number) => {
  currentPage.value = page
  await fetchArticles()
}



watch(() => route.params.diseaseId, (newId) => {
  if (newId) {
    diseaseId.value = parseInt(newId as string)
    fetchDiseaseData()
  }
})

onMounted(() => {
  fetchUserInfo()
  fetchDiseaseData()
})
</script>

<template>
  <div class="min-h-screen flex flex-col">
    <!-- Header -->
    <!-- 登录注册 -->
    <header class="header bg-white p-4 shadow-md flex justify-between items-center">

      <div class="container flex items-center">
        <div class="links-container">
          <a href="#" class="flex items-center text-gray-600 hover:text-blue-500">
            <i class="icon-download"></i>
            <span class="ml-1">下载App</span>
          </a>
          <a href="#" class="text-blue-500 font-bold hover:underline">栏目收费说明</a>
        </div>
        <!-- 使用 v-if/v-else 来条件渲染登录/注册按钮或用户信息 -->
        <div v-if="!username" class="lrcs items-center space-x-4"> <!-- Flex 布局让内容一行排列 -->
          <RouterLink class="btn-login"
            :to="{ name: 'Login', query: { redirecturl: router.currentRoute.value.fullPath } }">登录</RouterLink>
          <RouterLink class="btn-register" to='/register'>注册</RouterLink>
        </div>
        <div v-else class="user-info flex items-center space-x-3"> <!-- 用户信息 -->
          <img :src="avatar" alt="用户头像" class="user-avatar w-8 h-8 rounded-full" />
          <span>{{ username }}</span>
          <span class="text-logout" @click="logout">退出</span>
        </div>

      </div>
    </header>

    <!-- Search -->
    <div class="search-header">
      <div class="search-wrapper">
        <h1 class="text-a">丁香医生</h1>
        <input type="text" v-model="searchQuery" placeholder="搜索疾病、医院、药品" class="search-input" />
        <button class="search-button">搜索</button>
      </div>
    </div>

    <!-- Navigation -->
    <nav class="main-nav">
      <router-link v-for="item in navigationItems" :key="item.name" :to="item.link" class="nav-link">
        {{ item.name }}
      </router-link>
    </nav>

    <!-- Main Content -->
    <main class="container mx-auto px-4">
      <!-- Breadcrumb -->
      <div class="breadcrumb my-4">
        <a href="/" class="text-primary">首页</a> >
        <span>健康百科目录</span> >
        <span v-if="disease">{{ disease.name }}</span>
      </div>

      <!-- Disease Categories -->
      <div class="disease-categories">
        <button v-for="d in diseases" :key="d.id" :class="['category-btn', d.id === diseaseId ? 'active' : '']"
          @click="selectDisease(d)">
          {{ d.name }}
        </button>
      </div>

      <!-- Articles -->
      <div v-if="loading" class="loading">
        加载中...
      </div>
      <div v-else-if="error" class="error">
        {{ error }}
      </div>
      <div v-else class="articles-grid">
        <article v-for="article in articles" :key="article.id" class="article-card">
          <div class="article-image">
            <img :src="article.cover || '/default-cover.jpg'" :alt="article.name">
          </div>
          <div class="article-content">
            <!-- <h3 class="article-title">{{ article.name }}</h3> -->
            <router-link :to="`/message/${article.id}`"
              class="text-xl font-semibold text-black hover:text-green-500 block mb-3" target="_blank"
              rel="noopener noreferrer">
              <h3>{{ article.name }}</h3>
            </router-link>
            <div class="article-text" v-html="article.content"></div>
          </div>
        </article>
      </div>

      <!-- Pagination -->
      <div class="pagination" v-if="totalPages > 1">
        <button v-for="page in totalPages" :key="page" :class="['page-btn', currentPage === page ? 'active' : '']"
          @click="changePage(page)">
          {{ page }}
        </button>
      </div>
    </main>

    <!-- Footer -->
    <footer class="mt-auto">
      <div class="bottom-links">
        <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
        <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
        <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
        <a href="mailto:doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
        <a target="_blank">客服电话：0571-22931767</a>
      </div>
    </footer>
  </div>
</template>

<style scoped>
/* 登录 */
.header {
  background-color: #f7f7f7;
  color: rgba(0, 0, 0, 0.5);
  box-shadow: 0 3px 3px rgba(0, 0, 0, 0.1);
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.header a {
  /* a标签默认有下划线，删除下划线 */
  text-decoration: none;
  /* 字体颜色 */
  color: #666;
  /* 字体大小 */
  font-size: 14px;
  display: flex;
  align-items: center;
  /* 用于定义元素从一种样式过渡到另一种样式时的动画效果 */
  transition: color 0.3s ease;
}

.header a:hover {
  color: #00b38a;
  /* Match green color on hover */
}

.header a.text-blue-500 {
  color: #00b38a;
  /* Green color for special links */
  font-weight: bold;
  margin-left: 16px;
}

.text-logout {
  margin-left: 16px;
  background-color: transparent;
  /* 透明背景 */
  border: none;
  /* 无边框 */
  color: #666666;
  /* 文本颜色与下载链接一致 */
  padding: 0;
  /* 移除内边距 */
  font-size: 14px;
  font-weight: normal;
  /* 正常字体粗细 */
  cursor: pointer;
  text-decoration: none;
  /* 移除下划线 */
  transition: color 0.3s ease;
  /* 颜色过渡效果 */
}

.text-logout:hover {
  color: #00b38a;
  text-decoration: underline;

}

.container {
  display: flex;
  align-items: center;
  /* justify-content: center;
  flex-direction: column; */
  flex-wrap: wrap;

  gap: 16px;
  margin-left: 350px;
  margin-right: 350px;

}

/* 可以添加一个包含栏目、下载等链接的容器样式 */
.links-container {
  display: flex;
  align-items: center;
  /* 之间的间隔 */
  border: none;
}

.btn-login {
  background-color: transparent;
  /* 透明背景 */
  border: none;
  /* 无边框 */
  color: #666666;
  /* 文本颜色与下载链接一致 */
  padding: 0;
  /* 移除内边距 */
  font-size: 14px;
  font-weight: normal;
  /* 正常字体粗细 */
  cursor: pointer;
  text-decoration: none;
  /* 移除下划线 */
  transition: color 0.3s ease;
  /* 颜色过渡效果 */
}

.btn-register {
  background-color: transparent;
  /* 透明背景 */
  border: none;
  /* 无边框 */
  color: #666666;
  /* 文本颜色与下载链接一致 */
  padding: 0;
  /* 移除内边距 */
  font-size: 14px;
  font-weight: normal;
  /* 正常字体粗细 */
  cursor: pointer;
  text-decoration: none;
  /* 移除下划线 */
  transition: color 0.3s ease;
  /* 颜色过渡效果 */
  margin-left: 13px;
}

.lrcs {
  display: flex;
  align-items: center;

}

/* 添加伪类来模仿下载链接的hover效果 */
.btn-login:hover,
.btn-register:hover {
  color: #00b38a;
  /* 悬停时变为绿色 */
  text-decoration: underline;
  /* 悬停时添加下划线 */
}

/* User Info Styling */
.user-info {
  display: flex;
  align-items: center;
}

.user-info .user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  /* Circular avatar */
  object-fit: cover;

}

.user-info span {
  font-size: 14px;
  font-weight: 500;
  color: #333333;
}

.btn-primary {
  margin-right: 10px;
}
/* 超链接 */
a {
  color: black;
}

a:hover {
  color: #00b38a;
}

.text-a {
  font-size: 32px;
  font-weight: 700;
  color: #00b38a;
  margin: 0 auto;
  letter-spacing: 1px;
}

.search-header {
  background-color: #fff;
  padding: 20px 0;
}

.search-wrapper {
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  gap: 10px;
}

.search-input {
  flex: 1;
  padding: 12px 20px;
  border: 2px solid #00b38a;
  border-radius: 24px;
  font-size: 16px;
  outline: none;
}

.search-button {
  padding: 12px 30px;
  background-color: #00b38a;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-size: 16px;
}

.main-nav {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 0;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.nav-link {
  padding: 6px 16px;
  color: #666;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.2s;
}

.nav-link:hover {
  color: #00b38a;
}

.disease-categories {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 20px 0;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.category-btn {
  padding: 8px 16px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 20px;
  color: #666;
  cursor: pointer;
  transition: all 0.2s ease;
}

.category-btn:hover {
  background-color: #e0f2f1;
  color: #00b38a;
}

.category-btn.active {
  background-color: #00b38a;
  color: white;
  border-color: #00b38a;
}

.text-c {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #00b38a;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn:hover {
  background-color: #00b38a;
}

.btn:focus {
  outline: none;
}



.articles-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 24px;
  margin: 24px 0;
}

.article-card {
  display: flex;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.article-image {
  width: 200px;
  height: 150px;
  flex-shrink: 0;
}

.article-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.article-content {
  flex: 1;
  padding: 20px;
}

.article-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.article-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin: 24px 0;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.page-btn.active {
  background-color: #00b38a;
  color: white;
  border-color: #00b38a;
}

.bottom-links {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
  padding: 24px;
  background-color: #f5f5f5;
}

.bottom-links a {
  color: #666;
  text-decoration: none;
  padding: 4px 8px;
}

.breadcrumb {
  color: #666;
}

.breadcrumb a {
  color: #00b38a;
  text-decoration: none;
}

.loading,
.error {
  text-align: center;
  padding: 40px;
  color: #666;
}

.error {
  color: #dc3545;
}
</style>